#include <iostream>
#include <unistd.h>
#include <pthread.h>

using namespace std;

//1.线程谁先运行与调度器相关
//2.线程一旦异常，都可能导致整个进程整体退出
//3.线程输入和返回值的问题
//4.线程异常退出
void* threadRoutine(void* args)
{
    int i = 0;
    int* data = new int[10];
    while (true)
    {
        cout << "新线程 : " << (char*)args << " running ..." << endl;
        sleep(1);
        data[i] = i;
        if (i++ == 10) break;
    }
    cout << "new thread quit" << endl;
    //pthread_exit((void*)13);//线程退出
    return (void*)data;//返回给pthread_join
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, nullptr, threadRoutine, (void*)"thread 1");

    int* ret = nullptr;

    pthread_cancel(tid);//返回值为PTHREAD_CANCELD 就是-1

    pthread_join(tid, (void**)&ret);//默认会阻塞等待新线程退出

    cout << "main thread wait done ... main quit ... : new thread quit : " <<  endl;

    for (int i = 0; i < 10; i++)
    {
        cout << ret[i] << " ";
    }
    cout << endl;
    //3.线程在创建并执行的时候，线程也是需要等待的，如果主程如果不等待
    //即会引起僵尸进程的问题，导致内存泄露
    // while (true)
    // {
    //     cout << "main线程 : " << " running ..." << endl;
    //     sleep(1);
    // }

    return 0;
}